﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;


/// <summary>
/// WORK TO DO
///     Check Fields before Update User Information
///     
/// </summary>


public partial class Admin_Users : System.Web.UI.Page
{
    ILE_Global ileGlobal = new ILE_Global();
    UsersBLL usersLogic = new UsersBLL();
    ClassBLL classLogic = new ClassBLL();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //FillDDListUsernameByAccountType("Instructor");
        }
    }

    protected void FillDDListUsernameByAccountType(string AccountType)
    {
        ddlistEditUserUsersList.Items.Clear();

        Users.UsersDataTable users = usersLogic.GetUsersByAccountType(AccountType);

        if (users.Count == 0)
        {
            ListItem newListItem = new ListItem("--No Users--", "0");
            ddlistEditUserUsersList.Items.Add(newListItem);
        }
        else
        {
            ListItem newListItem = new ListItem("--Please Choose--", "0");
            ddlistEditUserUsersList.Items.Add(newListItem);
        }
        foreach (Users.UsersRow user in users)
        {
            ListItem newListItem = new ListItem();
            newListItem.Text = user.FirstName + " " + user.LastName + " (" + user.Username + ")";
            newListItem.Value = user.UserID.ToString();
            ddlistEditUserUsersList.Items.Add(newListItem);
        }
    }

    protected void btnOpenAddUser_Click(object sender, EventArgs e)
    {
        MultiViewUsers.ActiveViewIndex = 0;
    }

    protected void btnAddUser_Click(object sender, EventArgs e)
    {
        string FirstName = txtAddUserFirstName.Text;
        string LastName = txtAddUserLastName.Text;
        string Email = txtAddUserEmail.Text;
        string Username = txtAddUserNetworkID.Text;
        string AccountType = String.Empty;

        bool IsActive = chkboxAddUserIsActive.Checked;
        bool IsAdmin = chkboxAddUserIsAdmin.Checked;

        if (IsAdmin)
        {
            AccountType = "Admin";
        }
        else
        {
            AccountType = "Instructor";
        }

        try
        {
            if (usersLogic.IsUserInTable(Username) == 0)
            {
                bool result = false;
                result = usersLogic.InsertUser(Username, AccountType, FirstName, LastName, String.Empty, Email, 0) != 0;
                if (result)
                {
                    // *SteveMsg
                    string modalPopupMsg = "Successfully added a user.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 1);
                    ResetAddUserFields();
                }
                else
                {
                    string modalPopupMsg = "Failed to add a user.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 2);
                }
            }
            else if (usersLogic.IsUserInTable(Username) == 1)
            {
                bool result = false;
                result = usersLogic.UpdateUserByUsername(AccountType, FirstName, LastName, String.Empty, Email, IsActive, 0, Username);
                if (result)
                {
                    // *SteveMsg
                    string modalPopupMsg = "Successfully added a user (by updating).";
                    ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 1);
                    ResetAddUserFields();
                }
                else
                {
                    string modalPopupMsg = "Failed to add a user.";
                    ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 2);
                }
            }
            else
            {
                string modalPopupMsg = "Failed to add a user. (There was an error. Please try again.";
                ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 2);
            }
        }
        catch (Exception ex)
        {
            ileGlobal.RecordError("Admin/Users.aspx.cs:btnAddUser_Click:001", "Could not insert a user.", 3, Request.Browser);

            string modalPopupMsg = "Failed to add a user.";
            ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 2);
        }
    }

    protected void ResetAddUserFields()
    {
        txtAddUserEmail.Text = String.Empty;
        txtAddUserFirstName.Text = String.Empty;
        txtAddUserLastName.Text = String.Empty;
        txtAddUserNetworkID.Text = String.Empty;

        chkboxAddUserIsActive.Checked = true;
        chkboxAddUserIsAdmin.Checked = false;
    }

    protected void ResetEditUserFields()
    {
        txtEditUserEmail.Text = String.Empty;
        txtEditUserFirstName.Text = String.Empty;
        txtEditUserLastName.Text = String.Empty;
        txtEditUserUsername.Text = String.Empty;

        chkboxEditUserIsActive.Checked = true;
        chkboxEditUserIsAdmin.Checked = false;

        btnDeleteUser.Enabled = false;
    }

    protected void btnOpenEditUser_Click(object sender, EventArgs e)
    {
        FillDDListUsernameByAccountType("Instructor");
        MultiViewUsers.ActiveViewIndex = 1;
        ResetEditUserFields();
    }

    protected void rdobtnEditUserAccountType_SelectedIndexChanged(object sender, EventArgs e)
    {
        ResetEditUserFields();
        FillDDListUsernameByAccountType(rdobtnEditUserAccountType.SelectedValue);
    }

    protected void ddlistEditUserUsersList_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlistEditUserUsersList.SelectedIndex != 0)
        {
            Users.UsersRow user = usersLogic.GetUserByUserID(Convert.ToInt32(ddlistEditUserUsersList.SelectedValue));

            txtEditUserEmail.Text = user.Email;
            txtEditUserFirstName.Text = user.FirstName;
            txtEditUserLastName.Text = user.LastName;
            txtEditUserUsername.Text = user.Username;
            chkboxEditUserIsActive.Checked = user.IsEnabled;
            chkboxEditUserIsAdmin.Checked = (user.AccountType == "Admin");

            btnDeleteUser.Enabled = true;
        }
        else
        {
            ResetEditUserFields();
        }
    }

    protected void btnEditUser_Click(object sender, EventArgs e)
    {
        int UserID = Convert.ToInt32(ddlistEditUserUsersList.SelectedValue);

        string FirstName = txtEditUserFirstName.Text;
        string LastName = txtEditUserLastName.Text;
        string Email = txtEditUserEmail.Text;
        string Username = txtEditUserUsername.Text;
        bool IsActive = chkboxEditUserIsActive.Checked;
        bool IsAdmin = chkboxEditUserIsAdmin.Checked;
        string AccountType = chkboxEditUserIsAdmin.Checked ? "Admin" : "Instructor";


        bool result = false;
        result = usersLogic.UpdateUserByUserID(Username, AccountType, FirstName, LastName, String.Empty, Email, 0, IsActive, UserID);
        if (result)
        {
            // *SteveMsg
            string modalPopupMsg = "Successfully edited user information.";
            ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 1);
            FillDDListUsernameByAccountType(rdobtnEditUserAccountType.SelectedValue);
            ResetEditUserFields();
        }
        else
        {
            // *SteveMsg
            string modalPopupMsg = "Failed to edit user information.";
            ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 2);
        }
    }

    protected void btnDeleteUser_Click(object sender, EventArgs e)
    {
        bool result = false;

        result = usersLogic.DeleteUserByUserID(Convert.ToInt32(ddlistEditUserUsersList.SelectedValue));
        if (result)
        {
            string modalPopupMsg = "Successfully deleted user.";
            ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 1);
            FillDDListUsernameByAccountType(rdobtnEditUserAccountType.SelectedValue);
            ResetEditUserFields();
        }
        else
        {
            string modalPopupMsg = "Failed to delete user.";
            ModalPopupMessage.ShowModalPopup("ILE Message", modalPopupMsg, 2);
        }
    }
    protected void btnOpenEditClasses_Click(object sender, EventArgs e)
    {
        if (usersLogic.GetUsersByAccountType("Instructor").Count <= 0)
        {
            lblEditClassMsg.Visible = true;
        }
        else
        {
            lblEditClassMsg.Visible = false;
        }

        GridViewInstructors.DataBind();
        MultiViewUsers.ActiveViewIndex = 2;
    }

    protected void GridViewInstructors_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (GridViewInstructors.SelectedIndex != -1)
        {
            GridViewClasses.SelectedIndex = -1;
            GridViewClasses.Visible = true;
            PanelCurrentSection.Visible = false;
        }
        else
        {
            GridViewClasses.Visible = false;
            PanelCurrentSection.Visible = false;
        }
    }

    protected void GridViewClasses_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (GridViewClasses.SelectedIndex != -1)
        {
            _loadLstboxCurrentSection();
            PanelCurrentSection.Visible = true;
        }
        else
        {
            PanelCurrentSection.Visible = false;
        }
    }

    private void _loadLstboxCurrentSection()
    {
        int UserID = Convert.ToInt32(GridViewInstructors.SelectedValue.ToString());
        int CourseID = Convert.ToInt32(GridViewClasses.SelectedValue.ToString());

        Classes.Courses_SectionDataTable sections = classLogic.GetSectionsByCourseID(CourseID, false);

        Users._Relations_Course_UserDataTable relations = usersLogic.GetCourseUserRelationshipsByCourseIDAndUserIDAndType(CourseID, UserID, "Instructor");

        lstboxCurrentSection.Items.Clear();

        int index = 0;
        foreach (Classes.Courses_SectionRow section in sections)
        {
            string ClassTime = section.ClassTime.ToString() == String.Empty ? section.SectionNumber.ToString() : section.SectionNumber.ToString() + " (" + section.ClassTime.ToString() + ")";
            ListItem newItem = new ListItem(ClassTime, section.SectionNumber.ToString());
            lstboxCurrentSection.Items.Add(newItem);

            foreach (Users._Relations_Course_UserRow relation in relations)
            {
                if (section.SectionNumber == relation.SectionNumber)
                {
                    lstboxCurrentSection.Items[index].Selected = true;
                }
            }
            index++;
        }
    }


    protected void lnkbtnDeselectSection_Click(object sender, EventArgs e)
    {
        lstboxCurrentSection.SelectedIndex = -1;
    }

    protected void lnkbtnSelectAllSection_Click(object sender, EventArgs e)
    {
        foreach(ListItem item in lstboxCurrentSection.Items)
        {
            item.Selected = true;
        }
    }

    protected void btnViewByInstructorUpdate_Click(object sender, EventArgs e)
    {
        int UserID = Convert.ToInt32(GridViewInstructors.SelectedValue.ToString());
        int CourseID = Convert.ToInt32(GridViewClasses.SelectedValue.ToString());

        // Currently, it deletes all the relations..
        usersLogic.DeleteCourseUserRelationsByCourseIDAndUserIDAndType(CourseID, UserID, "Instructor");
        usersLogic.DeleteCourseUserRelationsByCourseIDAndUserIDAndType(CourseID, UserID, "Student");

        bool result = true;
        foreach(ListItem listItem in lstboxCurrentSection.Items)
        {
            if(listItem.Selected)
            {
                int SectionNumber = Convert.ToInt32(listItem.Value);
                //Users._Relations_Course_UserRow relation = usersLogic.GetCourseUserRelationshipsByCourseIDAndSectionNumberAndUserID(CourseID, SectionNumber, UserID);
                //if(relation != null)
                //{
                //    usersLogic.DeleteCourseUserRelationsByCourseIDAndSectionNumberAndUserID(CourseID, SectionNumber, UserID);
                //}
                //else
                //{
                    if (!usersLogic.InsertCourseUserRelation(CourseID, SectionNumber, UserID, "Instructor", 0))
                    {
                        result = false;
                    }
                //}
            }
        }

        if (result)
        {
            // *SteveMsg
            ModalPopupMessage.ShowModalPopup("ILE Message", "Updated Successfully", 1);
        }
        else
        {
            // *SteveMsg
            ModalPopupMessage.ShowModalPopup("ILE Message", "Update failed", 2);
        }
        
    }
    protected void GridViewClasses2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (GridViewInstructors.SelectedIndex != -1)
        {
            GridViewClasses.SelectedIndex = -1;
            GridViewClasses.Visible = true;
            PanelCurrentSection.Visible = false;
        }
        else
        {
            GridViewClasses.Visible = false;
            PanelCurrentSection.Visible = false;
        }
    }
    protected void rdobtnsFilterAccountType_SelectedIndexChanged(object sender, EventArgs e)
    {
        RadioButtonList rdobtns = (RadioButtonList)sender;
        if (rdobtns.SelectedIndex == 0)
        {
            GridViewInstructors.DataSourceID = "ObjectDataSourceInstructors";
            GridViewInstructors.DataBind();
        }
        else
        {
            GridViewInstructors.DataSourceID = "ObjectDataSourceAdmins";
            GridViewInstructors.DataBind();
        }

        GridViewInstructors.SelectedIndex = -1;
        GridViewClasses.Visible = false;
        PanelCurrentSection.Visible = false;
    }
}
